//
// Created by Zhao Ziqiu on 2021/8/22.
//

#include <napi.h>
#include "player.h"
#include <iostream>
using namespace Napi;
using namespace std;

Object Player::Init(Napi::Env env, Object exports) {
    Function func = DefineClass(env, "Player", {
        InstanceMethod("prepare", &Player::Prepare)
    });
    auto *constructor = new FunctionReference();
    *constructor = Persistent(func);
    env.SetInstanceData(constructor);
    exports.Set("Player", func);
    return exports;
}
Player::Player(const CallbackInfo& info)
        : ObjectWrap<Player>(info) {
    playerImpl = new PlayerImpl;
}

Napi::Value Player::Prepare(const CallbackInfo &info) {
    if (info.Length() != 1 || !info[0].IsString()) {
        Error err = Error::New(info.Env(), "Require only one parameter which type is String");
        err.ThrowAsJavaScriptException();
        return info.Env().Undefined();
    }
    String url = info[0].As<String>();
    prepareWorker = new PrepareWorker(info.Env(), playerImpl,  url.Utf8Value());
    prepareWorker->Queue();
    return prepareWorker->mDeferred.Promise();
}

Player::~Player() {
    delete playerImpl;
}

